package org.dtrd.modules.device.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import org.dtrd.base.BaseController;
import org.dtrd.common.api.vo.Result;
import org.dtrd.config.system.Constant;
import org.dtrd.modules.device.entity.request.SGBLDataRequest;
import org.dtrd.modules.device.util.SGBLBLEParseUtil;
import org.dtrd.modules.record.entity.bean.SugarValueBean;
import org.dtrd.modules.record.service.ISugarRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

import static org.dtrd.config.system.SystemState.ResponseState.STATE_OPERATION_FAILURE;
import static org.dtrd.config.system.SystemState.ResponseState.STATE_PARAMS_MISSING;

/**
 * @author qr
 * @date 2022/2/8 11:00
 */
@Api(tags = "瞬感伴侣")
@RestController
@RequestMapping("/device/sgbl")
public class SGBLController extends BaseController {

    @Autowired
    private ISugarRecordService sugarRecordService;

    @PostMapping("/synch")
    public Result<?> synchSGBLSugarValueBLE(@RequestBody SGBLDataRequest request) {
        Integer patientId = request.getPatientId();
        String hex = request.getContent();
        // 空参校验
        if (isIntParamInvalid(patientId)
                || StrUtil.isBlank(hex)) {
            return error(STATE_PARAMS_MISSING);
        }
        String[] split = hex.split(",");
        List<SugarValueBean> infoList = new ArrayList<>(split.length);
        List<SugarValueBean> tmpList;
        for (String s : split) {
            tmpList = SGBLBLEParseUtil.getBloodSugar(s);
            if (CollectionUtil.isNotEmpty(infoList)) {
                infoList.addAll(tmpList);
            }
        }
        // 保存列表数据
        boolean result = sugarRecordService.synchSGBLSugarList(infoList, Constant.SugarSourceType.SOURCE_SGBL_BLE.getType(), patientId);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }
}
